package com.prb.proivder.one.server;

import com.prb.proivder.one.handler.RequestHandler;
import com.prb.common.code.SmartCarDecoder;
import com.prb.common.code.SmartCarEncoder;
import com.prb.proivder.one.provider.ProviderLoader;
import com.prb.register.factory.RpcRegistryFactory;
import com.prb.register.register.RpcRegistryHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class RpcServer implements InitializingBean, DisposableBean {

    @Autowired
    private RpcRegistryFactory registryFactory;


    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;


    public void startServer(String ip , Integer port) throws Exception {

        try{
            registerService(ip , port);

            //启动netty 监听 客户端请求 ， 进行服务处理

            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new SmartCarDecoder());
                            pipeline.addLast(new SmartCarEncoder());
                            pipeline.addLast(new RequestHandler());
                        }
                    });

            System.out.println("=============开始绑定=============");
            ChannelFuture sync = serverBootstrap.bind(ip , port).sync();
            //this.registry(ip, port, applicationName, config.getServices());
            System.out.println("start ========================= server");
            sync.channel().closeFuture().sync();

        } finally {
            // 优雅释放线程资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }


    }



    @Override
    public void destroy() throws Exception {

        System.out.println("stop server");
        if (null != bossGroup) {
            bossGroup.shutdownGracefully();
        }
        if (null != workerGroup) {
            workerGroup.shutdownGracefully();
        }
    }

    public static String name = "server2";
    @Override
    public void afterPropertiesSet() throws Exception {


        startServer("127.0.0.1" , 9010);
    }


    // 往 注册中心zk 暴露服务
    private void registerService(String ip , Integer port) throws Exception {

        //往注册中心 暴露服务
        Map<String, Object> registerLocals = ProviderLoader.getInstanceCacheMap();

        RpcRegistryHandler registryHandler = registryFactory.getObject();

        registerLocals.entrySet().stream().forEach(registerLocal ->registryHandler.registry(registerLocal.getKey() , ip , port));

    }


}


